package com.googlecode.recycled.lang.jse.api.io;

import com.google.common.io.Files;
import com.googlecode.recycled.lang.jse.lang.Stacktraces;
import org.apache.commons.lang.UnhandledException;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;

public class FilesExt {

    private FilesExt() {
    }

    public static final FileFilter FILE_FILTER_DICTIONARY = new FileFilter() {

        @Override
        public boolean accept(File file) {
            return file.isDirectory();
        }

    };

    public static final FileFilter FILE_FILTER_FILE = new FileFilter() {

        @Override
        public boolean accept(File file) {
            return file.isFile();
        }

    };

    public static final FileFilter FILE_FILTER_NON_EMPTY = new FileFilter() {

        @Override
        public boolean accept(File file) {
            return file.length() > 0;
        }

    };

    public static String toString(File file) {
        try {
            return Files.toString(file, CharStreamsExt.DEFAULT_CHARSET);
        } catch (IOException e) {
            throw new UnhandledException(e);
        }
    }

    public static void assertDirectory(File directory) {
        if (directory.isFile()) {
            throw new RuntimeException("File with given path exists: " + directory.getAbsolutePath());
        }
        if (!directory.exists() && !directory.mkdirs()) {
            throw new RuntimeException("Cannot create directory: " + directory.getAbsolutePath());
        }
    }

    public static void assertDirectory(String directoryPath) {
        assertDirectory(new File(directoryPath));
    }

    public static File createTempFile() {
        try {
            String fileName = Stacktraces.previousClassName().getName() + "." + Stacktraces.previousMethodName() + "_";
            return File.createTempFile(fileName, ".tmp");
        } catch (IOException e) {
            throw new UnhandledException(e);
        }
    }

}
